package com.feonix.common.service;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.feonix.common.BaseInfo;
import com.feonix.common.basedao.Entity;
import com.feonix.common.basedao.EntityManager;
import com.feonix.common.basedao.SqlType;
import com.feonix.common.dao.EntityORMDAO;
import com.feonix.common.util.StringUtil;

@Service
public class EntityORMService {
	private Log logger = LogFactory.getLog(super.getClass());

	@Autowired
	private EntityORMDAO entityORMDAO;

	public void addTableBeforeCheck(Class<?> paramClass, Entity paramEntity) {
		String tableName = paramEntity.getTableName();
		if (StringUtil.isNotEmpty(tableName)) {
			boolean bool = this.entityORMDAO.existsTable(tableName);
			if (!(bool)) {
				logger.info("table:[" + tableName + "] is not exsit, start create this table");
				addTable(paramClass);
			}
		}
	}

	private void addTable(Class<?> paramClass) {
		Map<SqlType, String> entities = EntityManager.getEntitySql(paramClass);
		String table = entities.get(SqlType.TABLE);
		String index = entities.get(SqlType.INDEX);
		if (StringUtil.isNotEmpty(table)) {
			this.entityORMDAO.executeForDDL(table);
		}

		String[] indexs;
		String trigger;
		if (StringUtil.isNotEmpty(index)) {
			indexs = StringUtil.split(index, ";");
			for (String str : indexs) {
				this.entityORMDAO.executeForDDL(str);
			}
		}
		if (BaseInfo.getDbType() == 1) {
			String seq = entities.get(SqlType.SEQ);
			trigger = entities.get(SqlType.TRIGGER);
			String enableSeq = (String) entities.get(SqlType.ENABLE_SEQ);
			if ((StringUtil.isEmpty(seq)) || (StringUtil.isEmpty(trigger)) || (StringUtil.isEmpty(enableSeq))) {
				return;
			}

			this.entityORMDAO.executeForDDL(seq);
			this.entityORMDAO.executeForDDL(trigger);
			this.entityORMDAO.executeForDDL(enableSeq);
		}
	}
}
